importPackage(java.lang);
importPackage(java.io);

load('tools/js/defaults.js');

function listDependencies(moduleObject, array) {
	var dependencies = array || [],
		requirements = moduleObject['requires'];

	if (requirements) {
		
		for (var i = 0; i < requirements.length; i++) {
			var requirement = requirements[i],
				requirementModule = NOKIA_DEFAULTS.modules[requirement];

			listDependencies(requirementModule, dependencies);
		}

	}

	if (moduleObject.getPath()) {
		dependencies.push(moduleObject);
	}

	return dependencies;
};

function copydependencies(components) {
	
	for (var k = 0; k < components.length; k++) {
		
		System.out.println("Copying component: " + components[k]);
		
		if (components[k] == 'all') {
			
			var depends = [];
			
			for (var w in NOKIA_DEFAULTS.modules) {
				
				depends = depends.concat( listDependencies( NOKIA_DEFAULTS.modules[w] ) );
				
			}

		} else {
			
			var depends = listDependencies(NOKIA_DEFAULTS.modules[components[k]]);

		}
		
		for (var i = 0; i < depends.length; i++) {
			var path = depends[i].getPath();
			var filePath = path.substr(path.lastIndexOf('/') + 1, path.length);
			
			var sourcePath = depends[i].type == 'css' ? '../themes/nokia/base/' : '../src/';
			var buildPath = depends[i].type == 'css' ? 'Guarana/themes/nokia/base/' : 'Guarana/lib/';
			
			try {
				
				var file = new File(sourcePath + filePath);
				
				var reader = new BufferedReader(new FileReader(file));
				
				var line = null;
				var buffer = new StringBuffer(file.length());
				
				while( (line = reader.readLine()) != null) {
					buffer.append(line);
					buffer.append("\n");
				}
				
				var fileContent = buffer.toString();
				  
			    // Create file 
			    var fstream = new FileWriter(buildPath + filePath);
			    var out = new BufferedWriter(fstream);
			    
			    // Write File
			    out.write(fileContent);
			    
			    //Close the output stream
			    out.close();
		    } catch (e) {
		      System.err.println("Error: " + e);
		    }
			
		}
		
	}
	
}

copydependencies(arguments[0].split('_'));
